package uiao.step1_failure;

import uiao.BankService;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Description: 转账操作
 * @Param:
 * @return:
 * @Author: cuihao
 * @Date: 2019/9/10
 */
public class FailureBankService implements BankService {
    /**
     * failureBankDao内也有一个dataSource
     */
    private FailureBankDao failureBankDao;
    /**
     * failureInsuranceDao内也有一个dataSource
     */
    private FailureInsuranceDao failureInsuranceDao;

    private DataSource dataSource;

    public FailureBankService(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * 转账操作会生成三个Connection
     *
     * @param fromId
     * @param toId
     * @param amount
     */
    @Override
    public void transfer(int fromId, int toId, int amount) {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);

            // 使用单独的connection
            failureBankDao.withdraw(fromId, amount);

            // 使用单独的connection
            failureInsuranceDao.deposit(toId, amount);

            connection.commit();
        } catch (Exception e) {
            try {
                assert connection != null;
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            try {
                assert connection != null;
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public void setFailureBankDao(FailureBankDao failureBankDao) {
        this.failureBankDao = failureBankDao;
    }

    public void setFailureInsuranceDao(FailureInsuranceDao failureInsuranceDao) {
        this.failureInsuranceDao = failureInsuranceDao;
    }
}
